# -*- coding:utf-8 -*-

## =====================================================================
## Copyright (C) 2007-2011  Jean-Philippe GOLAY
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## =====================================================================


from Tkinter import *
import Pmw
from tkMessageBox import *

from Persistance import *
from iArea import SearchAreaGUI
from iNotes import NotesGUI

class PlaceGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Résidence")
		self.balloon=balloon
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.imgNotes=PhotoImage(file="img/edit.gif")
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.listObject=[City]
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Place-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Place-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tPlaceGUI\tStart")
		self.makePlace()

	# DEBUT  gestion module Place ----------------------------------------------------------------------------------------------------------------------------
	def clearFieldPlace(self):
		for value in self.placeValues:
			value.set("")
		self.listObject=[City]

	def selectPlace(self, event):
		self.clearFieldPlace()
		result = Place.select(Place.q.id==self.idListPlace[int(self.listPlace.curselection()[0])])
		for row in result:
			self.selectedPlace = row
		self.placeValues[0].set(self.selectedPlace.company)
		self.placeValues[1].set(self.selectedPlace.address1)
		if self.selectedPlace.address2 != None:self.placeValues[2].set(self.selectedPlace.address2)
		if self.selectedPlace.tel != None:self.placeValues[8].set(self.selectedPlace.tel)
		if self.selectedPlace.fax != None:self.placeValues[9].set(self.selectedPlace.fax)
		if self.selectedPlace.cell != None:self.placeValues[10].set(self.selectedPlace.cell)
		if self.selectedPlace.email != None:self.placeValues[11].set(self.selectedPlace.email)
		if self.selectedPlace.description != None:self.placeValues[12].set(self.selectedPlace.description)
		if self.selectedPlace.notes != None:self.placeValues[13].set(self.selectedPlace.notes)
		self.listObject[0]=self.selectedPlace.city
		self.placeValues[3].set(self.listObject[0].name)
		self.placeValues[4].set(self.listObject[0].zipCode.code)
		self.placeValues[5].set(self.listObject[0].zipCode.county.name)
		self.placeValues[6].set(self.listObject[0].zipCode.county.state.name)
		self.placeValues[7].set(self.listObject[0].zipCode.county.state.country.name)
		self.deletePlaceBt.config(state=NORMAL)

	def searchPlace(self, event=None):
		if self.searchPlaceValue.get() != "":
			self.listPlace.delete(0,END)
			self.idListPlace = []
			result = Place.select(Place.q.company.startswith(self.searchPlaceValue.get().encode("utf-8")), orderBy=Place.q.company)
			for row in result:
				self.listPlace.insert(END, row.company)
				self.idListPlace.append(row.id)
		else:
			self.listPlace.delete(0,END)
			self.idListPlace = []
			result = Place.select(orderBy=Place.q.company)
			for row in result:
				self.listPlace.insert(END, row.company)
				self.idListPlace.append(row.id)

	def makePlace(self):
		leftFrame = Frame(self)
		# Fiche Résidence  (présentation colonne de gauche)
		Label(leftFrame, text=u"Résidence").pack()
		# Création des champs a renseigner pour un object Place
		placeLabels = (u"Nom", u"Adresse", u"Adresse", u"Ville", u"Code postal", u"Département", u"Région", u"Pays", u"Tél", u"Fax", u"Mobile", u"Email", u"Déscription", u"Notes")
		self.placeValues = [StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar()]
		count = 0
		for name in placeLabels:
			f = Frame(leftFrame)
			Label(f, width=12, text=name, anchor=W).pack(side=LEFT)
			if count==3:
				Entry(f, textvariable=self.placeValues[count], width=20 , state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				selectAreaBT=Button(f, image=self.imgSearch, command=self.ctrlArea)
				selectAreaBT.pack(side=RIGHT)
				self.balloon.bind(selectAreaBT, u"Séléctionner un lieu")
			elif count > 3 and count < 8: 
				Entry(f, textvariable=self.placeValues[count], state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
			elif count == 12: # Description
				Entry(f, textvariable=self.placeValues[count], width=20).pack(side=LEFT, fill=X)
				myDescription=Button(f, image=self.imgNotes, command=lambda x=self.placeValues[count]:self.ctrlNotes(x,u"Déscription"), padx=4, pady=1)
				myDescription.pack(side=RIGHT)
				self.balloon.bind(myDescription, u"Détails de la déscription")
			elif count == 13: # Notes
				Entry(f, textvariable=self.placeValues[count], width=20).pack(side=LEFT, fill=X)
				myNotes=Button(f, image=self.imgNotes, command=lambda x=self.placeValues[count]:self.ctrlNotes(x,u"Notes"),  padx=4, pady=1)
				myNotes.pack(side=RIGHT)
				self.balloon.bind(myNotes, u"Détails de la note")
			else: 
				Entry(f, textvariable=self.placeValues[count], width=24).pack(side=LEFT, fill=X)
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.savePlaceBt=Button(s, image=self.imgSave, command=self.createPlace)
		self.savePlaceBt.bind("<Return>", self.createPlace)
		self.savePlaceBt.pack(side=LEFT)
		self.balloon.bind(self.savePlaceBt, u"Enregistrer")
		self.deletePlaceBt=Button(s, image=self.imgDelete, command=self.deletePlace, state=DISABLED)
		self.deletePlaceBt.bind("<Return>", self.deletePlace)
		self.deletePlaceBt.pack(side=LEFT)
		self.balloon.bind(self.deletePlaceBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Liste des Résidences existantes (présentation colonne de droite)
		rightFrame = Frame(self) 
		Label(rightFrame, text=u"Liste des Résidences").pack(side=TOP, fill=X)
		self.searchPlaceValue = StringVar()
		self.searchPlaceEt = Entry(rightFrame,  width=42, textvariable=self.searchPlaceValue, relief=GROOVE)
		self.searchPlaceEt.bind("<KeyRelease>", self.searchPlace)
		self.searchPlaceEt.pack(side=TOP, fill=X)
		s = Frame(rightFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listPlace = Listbox(s)
		self.listPlace.config(yscrollcommand=scrollbar.set,width=43, selectmode=SINGLE, height=18)
		self.listPlace.bind("<ButtonRelease-1>",self.selectPlace)
		scrollbar.config(command=self.listPlace.yview)
		self.listPlace.pack()
		s.pack(side=TOP, fill=X)
		rightFrame.pack(side=RIGHT, fill=BOTH)
		self.searchPlace()

	def ctrlArea(self):
		SearchAreaGUI(balloon=self.balloon, index=0, listObject=self.listObject, 
														fieldCity=self.placeValues[3], fieldZipCode=self.placeValues[4], 
														fieldCounty=self.placeValues[5], fieldState=self.placeValues[6], 
														fieldCountry=self.placeValues[7], log=self.log, path=self.path)

	def ctrlNotes(self,field,title):
		NotesGUI(field=field,title=title, log=self.log, path=self.path)
		
	def verifyPlace(self):
		if self.placeValues[0].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Nom (de la résidence) est obligatoire !\nMerci de le compléter.")
			return False
		elif self.placeValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le premier champ Adresse est obligatoire !\nMerci de le compléter.")
			return False
		elif self.placeValues[3].get() == "":
			showerror(u"Erreur de saisie", u"La séléction d'un lieu est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createPlace(self, event=None):
		if self.verifyPlace():
			if  self.deletePlaceBt.config()["state"][4] == "normal":
				self.modifyPlace()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme une nouvelle résidence ?\n" % self.placeValues[0].get()):
					Place(company=self.placeValues[0].get().encode("utf-8"),
						address1=self.placeValues[1].get().encode("utf-8"),
						address2=self.placeValues[2].get().encode("utf-8"),
						city=self.listObject[0],
						tel=self.placeValues[8].get().encode("utf-8"),
						fax=self.placeValues[9].get().encode("utf-8"),
						cell=self.placeValues[10].get().encode("utf-8"),
						email=self.placeValues[11].get().encode("utf-8"),
						description=self.placeValues[12].get().encode("utf-8"),
						notes=self.placeValues[13].get().encode("utf-8"),
						createDate=datetime.datetime.now()
					)
					self.searchPlace()
					self.clearFieldPlace()
				else:
					self.clearFieldPlace()

	def modifyPlace(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier la Résidence %s ?" % self.placeValues[0].get()):
			self.selectedPlace.company=self.placeValues[0].get().encode("utf-8")
			self.selectedPlace.address1=self.placeValues[1].get().encode("utf-8")
			self.selectedPlace.address2=self.placeValues[2].get().encode("utf-8")
			self.selectedPlace.city=self.listObject[0]
			self.selectedPlace.tel=self.placeValues[8].get().encode("utf-8")
			self.selectedPlace.fax=self.placeValues[9].get().encode("utf-8")
			self.selectedPlace.cell=self.placeValues[10].get().encode("utf-8")
			self.selectedPlace.email=self.placeValues[11].get().encode("utf-8")
			self.selectedPlace.description=self.placeValues[12].get().encode("utf-8")
			self.selectedPlace.notes=self.placeValues[13].get().encode("utf-8")
			self.deletePlaceBt.config(state=DISABLED)
			self.clearFieldPlace()
		else:
			self.deletePlaceBt.config(state=DISABLED)
			self.clearFieldPlace()

	def deletePlace(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer la Résidence %s ?\nCette opération est irréversible !" % self.placeValues[0].get()):
			Place.delete(self.selectedPlace.id)
			self.deletePlaceBt.config(state=DISABLED)
			self.searchPlace()
			self.clearFieldPlace()
		else:
			self.deletePlaceBt.config(state=DISABLED)
			self.clearFieldPlace()
	# FIN de la gestion du module Place -------------------------------------------------------------------------------------------------------------------

class PlaceListGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Liste des Résidences")
		self.balloon=balloon
		self.imgNew=PhotoImage(file="img/add_alternative_icon.gif")
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		## # Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Place-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Place-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tPlaceListGUI\tStart")
		self.makeListPlace()

	def selectListPlace(self, event):
		if self.listListPlace.get(0)!="":
			result = Place.select(Place.q.id==self.idListListPlace[int(self.listListPlace.curselection()[0])])
			for row in result:
				self.listObject[self.index]=row
				self.field.set(row.company)
				self.destroy()

	def searchListPlace(self, event=None):
		if self.searchListPlaceValue.get() != "":
			self.listListPlace.delete(0,END)
			self.idListListPlace = []
			result = Place.select(Place.q.company.startswith(self.searchListPlaceValue.get().encode("utf-8")), orderBy=Place.q.company)
			for row in result:
				self.listListPlace.insert(END, row.company)
				self.idListListPlace.append(row.id)
		else:
			self.listListPlace.delete(0,END)
			self.idListListPlace = []
			result = Place.select(orderBy=Place.q.company)
			for row in result:
				self.listListPlace.insert(END, row.company)
				self.idListListPlace.append(row.id)

	def makeListPlace(self):
		rightFrame = Frame(self)
		Label(rightFrame, text=u"Rechercher une Résidences").pack(side=TOP, fill=X)
		s = Frame(rightFrame)
		self.searchListPlaceValue = StringVar()
		self.searchListPlaceEt = Entry(s,  width=32, textvariable=self.searchListPlaceValue, relief=GROOVE)
		self.searchListPlaceEt.bind("<KeyRelease>", self.searchListPlace)
		self.searchListPlaceEt.pack(side=LEFT, fill=X)
		newPlaceBt=Button(s, image=self.imgNew, command=self.ctrlPlace)
		newPlaceBt.pack(side=RIGHT)
		self.balloon.bind(newPlaceBt, u"Créer une nouvelle Résidences")
		s.pack(side=TOP, fill=X)
		s = Frame(rightFrame)
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listListPlace = Listbox(s)
		self.listListPlace.config(yscrollcommand=scrollbar.set,width=33, selectmode=SINGLE, height=16)
		self.listListPlace.bind("<ButtonRelease-1>",self.selectListPlace)
		scrollbar.config(command=self.listListPlace.yview)
		self.listListPlace.pack()
		s.pack(side=TOP, fill=X)
		rightFrame.pack(side=RIGHT, fill=X)
		self.searchListPlace()

	def ctrlPlace(self):
		PlaceGUI(balloon=self.balloon, log=self.log, path=self.path)